﻿using System.Collections.Generic;
using System.Linq;
using AMM.Model;

namespace AMM.DataAccess.Config {
    public class FunctionRepository : BaseRepository<RoleFunction> {
        public List<Function> FetchFunctionList() {
            using (var ctx = this.Context) {
                return ctx.Functions.OrderBy(x => x.Sequence).ToList();
            }
        }

        public Function FetchFunctionByCode(string code) {
            using (var ctx = this.Context) {
                return ctx.Functions.FirstOrDefault(x => x.Code == code);
            }
        }

        public List<Function> FetchFunctionByRole(int roleId) {
            using (var ctx = this.Context) {
                var query = from a in ctx.RoleFunctions
                            join b in ctx.Functions on a.FunctionId equals b.FunctionId
                            where a.RoleId == roleId
                            select b;

                return query.OrderBy(x => x.Sequence).ToList();
            }
        }

        public List<Function> FetchFunctionByParentId(int parentId) {
            using (var ctx = this.Context) {
                return ctx.Functions
                    .Where(x => x.ParentFunctionId == parentId)
                    .OrderBy(x => x.Sequence)
                    .ToList();
            }
        }

        public List<RoleFunction> FetchRoleFunctionByCode(string code) {
            using (var ctx = this.Context) {
                var query = from a in ctx.RoleFunctions
                            join b in ctx.Functions on a.FunctionId equals b.FunctionId
                            where b.Code == code
                            select a;

                return query.ToList();
            }
        }
    }
}
